﻿using Architecture.Domain.Dto.Source;
using Architecture.Repository.Interface;
using Architercture.Domain.Service.IService;
using Swork03_28.Domain.TraceableInfos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architercture.Domain.Service.Impls
{
    public class DeepProcessService : IDeepProcessService
    {
        private readonly IDeepProcessRepository _deepRepository;

        public DeepProcessService(IDeepProcessRepository deepRepository)
        {
            _deepRepository = deepRepository;
        }

        //反填深加工信息
        public async Task<DeepProcess> GetDeepProcessInfo(string batchCode)
        {
            var info = await _deepRepository.GetValues(c => c.BatchCode.Equals(batchCode));
            //var res = info.FirstOrDefault() != null ? info.FirstOrDefault() : null;
            return info.FirstOrDefault();
        }
        //添加深加工信息
        public async Task<int> CreateDeepProcess(DeepProcess entity)
        {
            var res = await _deepRepository.CreateAsync(entity);
            return res;
        }
        //修改深加工信息
        public async Task<int> UpdateDeepProcess(DeepProcess entity)
        {
            var res = await _deepRepository.UpdateAsync(entity);
            return res;
        }

        public async Task<List<ImgDto>> GetCertificateList(string? batchCode)
        {
            var imgStr = await _deepRepository.GetValues(c => c.BatchCode.Equals(batchCode));
            //if(imgStr.FirstOrDefault() == null)
            //{
            //    await CreateFarmInfo(new Farm { BatchCode = batchCode });
            //    GetCertificateList(batchCode);
            //}
            if (imgStr.FirstOrDefault() == null || string.IsNullOrEmpty(imgStr.FirstOrDefault().Certification))
            {
                return new List<ImgDto>();
            }
            var imgList = imgStr.FirstOrDefault().Certification.Split(",").Select(c => new ImgDto
            {
                name = c,
                url = "https://localhost:44391/Img/" + c
            });
            return imgList.ToList();
        }

        public async Task<int> OperationImg(string? batchCode, string? imgUrls)
        {
            var infor = _deepRepository.GetValues(c => c.BatchCode.Equals(batchCode)).Result.FirstOrDefault();
            if (infor == null)
            {
                await CreateDeepProcess(new DeepProcess { BatchCode = batchCode });
                infor = _deepRepository.GetValues(c => c.BatchCode.Equals(batchCode)).Result.FirstOrDefault();
            }
            infor.Certification = imgUrls;
            int res = await _deepRepository.UpdateAsync(infor);
            return res;
        }
    }
}
